package com.ayf.payment.game.api.utils;

import com.ayf.payment.game.api.dto.MySmsXmlDTO;
import com.thoughtworks.xstream.XStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * User: rizenguo
 * Date: 2014/10/23
 * Time: 14:59
 */
public class KqXmlUtil {

    public static <T> T getObjectFromXML(String xmlRoot,String xml, Class<? extends T> tClass) {
        //将从API返回的XML数据映射到Java对象
        XStream xStreamForResponseData = new XStream();
        xStreamForResponseData.alias(xmlRoot, tClass);
        xStreamForResponseData.ignoreUnknownElements();//暂时忽略掉一些新增的字段
        return (T) xStreamForResponseData.fromXML(xml);
    }

    /**
     * JavaBean转换成xml
     * @param obj
     * @param encoding
     * @return
     */
    public static String convertToXml(Object obj, String encoding) {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);

            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * xml转换成JavaBean
     * @param xml
     * @param c
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T converyToJavaBean(String xml, Class<T> c) throws Exception {
        T t = null;
        try {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            throw new Exception("xml转换成JavaBean发生"+e.getClass().getName()+"异常");
        }
        return t;
    }

    public static void main(String[] args) {
        MySmsXmlDTO returnsms = getObjectFromXML("returnsms", "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
                "<returnsms>\n" +
                "<returnstatus>ok</returnstatus> ---------- 状态值：成功返回Success 失败返回：Faild\n" +
                "<message>12</message> ---------- 返回信息：见下表\n" +
                "<taskID>3</taskID>  -----------  返回本次任务的序列ID\n" +
                "</returnsms>", MySmsXmlDTO.class);
        System.out.println(returnsms);
    }
}

